<!<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:widget="http://www.netvibes.com/ns/">
  <head>
 
    <meta name="author" content="John Doe" />
    <meta name="description" content="A descriptive description" />
 
    <link rel="stylesheet" type="text/css" 
      href="http://www.netvibes.com/themes/uwa/style.css" />
    <script type="text/javascript" 
      src="http://www.netvibes.com/js/UWA/load.js.php?env=Standalone"></script>
 
    <title>Title of the Widget</title>
		
		



<script language="JavaScript" type="text/javascript">

/*
gadgets.Prefs.setMessages_({"total":"Total","second":"sec.","save":"Save","change":"Change","moveup":"Move up","prefsloading":"Loading preferences...","optionexpire":"strike","currencytip":"You can change the currency in gadget settings","show":"Show","cancel":"Cancel","changepercent":"Percent","loalert":"Low","hialert":"High","addstock":"Add","gadgetdesc":"Highly configurable list with unlimited number of stocks, options, ETFs. See chart and details for each stock. Calculate total value, earning and much more in your local currency.","help":"Help","initialloading":"Loading configured columns...","notused":"Not used","showprofit":"Show profit details","buyprice":"Buy price","value":"Value","valuetotal":"Total value","daylow":"Day low","exchange":"Exchange","showaddedit":"Show add/edit dialog","symbolsearchtip":"Enter symbol or company name","edittooltip":"Click to change this item","showsummary":"Show stock summary","symbol":"Symbol","dayearned":"Gain today","dayhigh":"Day high","loading":"Loading ...","currencyrate":"Exch.rate","dayopen":"Day open","enter":"Enter","lasttradetime":"Trade time","tradecost":"comm.","searchlimit":"Search is limited to 10 hits.","earnedtotal":"Total gain","column":"Column","month":"month","symbolprofittip":"Change quantity and price in profit details simply by clicking on the number you want to change","day":"day","ask":"Ask","profitsummary":"Profit summary","updateinterval":"Update","lasttrade":"Last","optioncallput":"call/put","dayclose":"Day close","lasttradedate":"Trade date","numberofstocks":"Qty.","currency":"Currency","minute":"min.","52weekrange":"52 week range","symbollookup":"Lookup","selectedcurrency":"Selected currency","dayvolume":"Volume","updatestock":"Update","customtitle":"Title","dayearnedtotal":"Total gain today","name":"Name","earned":"Gain","charttooltip":"Tooltip","bid":"Bid","notfound":"not found","dayrange":"Day range","retrystockloading":"Retrying stockdata request...","lastupdated":"Updated","50daymovingavg":"50 day avg.","shownews":"Show news","gotoggroups":"Discuss this gadget with the developer and other users","tickertrend":"Trend","200daymovingavg":"200 day avg.","flashing":"Flashing","months":"months","deletestock":"Remove","stockloading":"Awaiting stock data...","days":"days","chartsummary":"Summary","profitdetails":"Profit details","dayavgvolume":"Avg.vol.","previousclose":"Prev close","chart":"Chart","optionstrike":"strike","chartperiod":"Chart period","fontsize":"Font size","movedown":"Move down","gadgettitle":"Stock portfolio"});
*/
/* 
gadgets.Prefs.setDefaultPrefs_({"ChartScope":"3m",
"CustomTitle":"Stock portfolio",
"ShowNews":"0",
"FontSize":"11px",
"Column1":"6",
"Column2":"31",
"Column3":"17",
"Column4":"0",
"Column5":"0",
"StockTC":"",
"StockQtys":"",
"Flashing":"true",
"ChartType":"ToolTip",
"Currency":"-",
"StockLo":"",
"ChangeColumn":"3",
"GadgetVersion":"0",
"NameColumn":"2",
"StockSymbols":"",
"StockPrices":"",
"StockHi":"",
"ShowProfit":"Summary",
"UpdateInterval":"300000",
"SettingVersion":"0",
"StockCurrRates":"",
"campaign_1":"0"});

*/

//gadgets.io.preloaded_=[];
widget.setValue("ChartScope","3m");
widget.setValue("CustomTitle","Stock portfolio");
widget.setValue("ShowNews","0");
widget.setValue("FontSize","11px");
widget.setValue("Column1","6");
widget.setValue("Column2","31");
widget.setValue("Column3","17");
widget.setValue("Column4","0");
widget.setValue("Column5","0");
widget.setValue("StockTC","");
widget.setValue("StockQtys","");
widget.setValue("Flashing","true");
widget.setValue("ChartType","ToolTip");
widget.setValue("Currency","-");
widget.setValue("StockLo","");
widget.setValue("ChangeColumn","3");
widget.setValue("GadgetVersion","0");
widget.setValue("NameColumn","2");
widget.setValue("StockSymbols","");
widget.setValue("StockPrices","");
widget.setValue("StockHi","");
widget.setValue("ShowProfit","Summary");
widget.setValue("UpdateInterval","300000");
widget.setValue("SettingVersion","0");
widget.setValue("StockCurrRates","");
widget.setValue("campaign_1","0");
</script>


    <link rel="icon" type="image/png" 
      href="http://www.netvibes.com/favicon.ico" />
			
			<style type="text/css">body,td,div,span,p{font-family:arial,sans-serif;}a {color:#0000cc;}a:visited {color:#551a8b;}a:active {color:#ff0000;}body{margin: 0px;padding: 0px;background-color:white;}</style><script>window['__isgadget']=true;
			</script>
			
			
 <widget:preferences>
   <preference type="text" name="CustomTitle" label="CustomTitle"    defaultValue="Stock portfolio" />
   <preference type="text" name="ShowNews" label="ShowNews"    defaultValue="0" />
   <preference type="text" name="FontSize" label="FontSize"    defaultValue="11px" />
   <preference type="text" name="Column1" label="Column1"    defaultValue="6" />
   <preference type="text" name="Column2" label="Column2"    defaultValue="31" />
   <preference type="text" name="Column3" label="Column3"    defaultValue="17" />
   <preference type="text" name="Column4" label="Column4"    defaultValue="0" />
   <preference type="text" name="Column5" label="Column5"    defaultValue="0" />
   <preference type="text" name="StockTC" label="StockTC"    defaultValue="" />
   <preference type="text" name="StockQtys" label="StockQtys"    defaultValue="" />
   <preference type="boolean" name="Flashing" label="Flashing"    defaultValue="true" /> <!-- boolean -->
   <preference type="text" name="ChartType" label="ChartType"    defaultValue="ToolTip" />
   <preference type="text" name="Currency" label="Currency"    defaultValue="-" />
   <preference type="text" name="StockLo" label="StockLo"    defaultValue="" />
   <preference type="text" name="ChangeColumn" label="ChangeColumn"    defaultValue="3" />
   <preference type="text" name="GadgetVersion" label="GadgetVersion"    defaultValue="0" />
   <preference type="text" name="NameColumn" label="NameColumn"    defaultValue="2" /> <!-- int -->
   <preference type="text" name="StockSymbols" label="StockSymbols"    defaultValue="" />
   <preference type="text" name="StockPrices" label="StockPrices"    defaultValue="" />
   <preference type="text" name="StockHi" label="StockHi"    defaultValue="" />
   <preference type="text" name="ShowProfit" label="ShowProfit"    defaultValue="Summary" />
   <preference type="text" name="UpdateInterval" label="UpdateInterval"    defaultValue="300000" /> <!-- int -->
   <preference type="text" name="SettingVersion" label="SettingVersion"    defaultValue="0" />
   <preference type="text" name="StockCurrRates" label="StockCurrRates"    defaultValue="" />
   <preference type="text" name="CustomTitle" label="CustomTitle"    defaultValue="Stock portfolio" />
   <preference type="text" name="campaign_1" label="campaign_1"    defaultValue="0" />

 </widget:preferences>




<style type="text/css">
    .cellL{padding-right:2px;padding-left:2px;white-space:nowrap;text-align:left;}
    .cellC{padding-right:2px;padding-left:2px;white-space:nowrap;text-align:center;}
    .cellR{padding-right:2px;padding-left:2px;white-space:nowrap;text-align:right;}
    .def{font-family:sans-serif;}
    .loading{font-family:sans-serif;foreground:#666666;font-style:italic;font-size:11px;}
    .Footer{font-size:9px;font-family:sans-serif;padding:0px;margin:0px;}
    .Chart{display:none;filter:alpha(opacity=85);opacity:0.85;background-color:#FFFFFF;width:192;height:96;position:absolute;color:white;border:2px solid black;z-index:9999;}
    .SearchList{display:none;position:relative;border:1px solid black;z-index:9998;background-color:white;top:-1;}
    .HrDef{height:1px;margin-top:1px;margin-bottom:1px;margin-right:0px;margin-left:0px;}
    td.HiAlert{width:9px;background:url("http://stockportfoliogg.googlecode.com/svn/released/images/HiAlert9.gif");background-repeat:no-repeat;background-position:center;}
    td.LoAlert{width:9px;background:url("http://stockportfoliogg.googlecode.com/svn/released/images/LoAlert9.gif");background-repeat:no-repeat;background-position:center;}
    .mmlib_table109 {border-bottom: 1px solid #ddd;}
    a.prostyle:link {color: #0000FF; font-size:10px;font-family:sans-serif; text-decoration: underline}
    a.prostyle:active {color: #ff6909; font-size:10px;font-family:sans-serif; text-decoration: none}
    a.prostyle:visited {color: #254970; font-size:10px;font-family:sans-serif; text-decoration: none}
    a.prostyle:hover {color: #000080; font-size:10px;font-family:sans-serif; text-decoration: underline;}
  </style>
			
 
  </head>
<body dir="ltr">

<div id="promo"></div>
  <div id="StockData"><div class="loading">Krage...Loading configured columns...</div></div>
  <div class="Footer" id="Footer"></div>
  <div id="StockProfitDetails" style="display:none;width:100%;overflow:scroll;overflow-y:hidden;"></div>
  <div class="def" id="StockAdd" style="display:none;"></div>
  <div class="def" id="StockProfitSummary" style="display:none"></div>
  <div class="def" id="StockSummary" style="display:none;"><div class="loading">Loading ...</div></div>
  <div class="def" id="StockNews" style="display:none;"></div>
  <div id="disclaimer" nowrap=""><hr class="HrDef"><table border="0" cellpadding="0" cellspacing="0" width="100%"><TBODY><tr><td class="Footer" nowrap="" valign="middle" width="10%"><a href="http://sites.google.com/site/cnybroe/iGoogleStockGadget/disclaimer" target="_blank">Stock data, news and historical charts provided by </a></td><td><img alt="Yahoo" border="0" height="16" src="http://stockportfoliogg.googlecode.com/svn/released/images/Yahoo.gif" title="Yahoo" width="16"></td><td align="right" class="Footer" id="gVersion" nowrap="" valign="middle" width="90%">Version</td></tr></TBODY></table></div>
  <div id="debug" nowrap="" style="display:none;font-size:9pt;padding:5px;color:red;width:100%;height:200px;overflow:scroll"></div> 
  <script defer="defer" language="javascript" type="text/javascript">
  //var pref=new gadgets.Prefs(109);
  var fsize=widget.getValue("FontSize");
  var arrStockSymbols=new Array();
  var arrStockQtys=new Array();
  var arrStockPrices=new Array();
  var arrStockTC=new Array();
  var arrStockHi=new Array();
  var arrStockLo=new Array();
  var arrStocks=new Array();
  var arrStockCurrRates=new Array();
  var IMAGES_BASE = "http://stockportfoliogg.googlecode.com/svn/released/images/";
  var iVersion=1.29;
  var iPrefVersion=0;
  var bDataReady;
  var bTablesReady;
  var bAllReady;
  var iMaxStockNo=40;
  var sDefStocks="^GSPC,GOOG,-,EURUSD=X,XAU=X";
  var iStockCols=5;
  var iConfCols=0;
  var iSDRetry=0;
  var iTmrRetry;
  var debug=0;
  //Increase columnsNo from 5 to 6
  
  
  
  //gadgets.window.adjustHeight is called too many times at load. Must be fixed  

  function fnInit(){
    document.getElementById("gVersion").innerHTML='Version:'+iVersion;
    fnReadPrefs();
    fnLoad();
    setTimeout('fnMessage();_IG_Analytics("UA-2031644-1", "/Portfolio")',2000);
  }

  function fnLoad(){
    fnPrefsValidation(arrStockSymbols);
    fnLoadData();
    fnInsertTables();
  }
  function fnLoadData(){
    bDataReady=false;
    bAllReady=false;
    clearTimeout(iTmrRetry);
    iTmrRetry=setTimeout('fnRetry()',5000*(iSDRetry+1)); 
    var sTags='e1snp2c1cl1d1t1oghvpwabt7m8m6ms3p3e3c4x';
    var sSymb='';
    for(var i=0;i<arrStockSymbols.length;i++){
      sSymb+=arrStockSymbols[i]+',';
    }
    sSymb=sSymb.substr(0,sSymb.length-1);
    sSymb=sSymb.replace('^DJI','^DJX'); //^DJI hack

    var url='http://download.finance.yahoo.com/d?s='+sSymb+'&f='+sTags+'&CW='+Math.random()*1000;
   /* var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
    params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 60;
    gadgets.io.makeRequest(url,fnStockDataProxy,params);
*/
		UWA.Data.request(
      url,
   {
     method: 'get',
		 proxy: 'ajax',
     type: 'text',
     cache: 60,
     onComplete: fnStockDataProxy
   });
		
		
  }
  function fnStockDataProxy(stockData){
    var arrLines=new Array();
    var arrLineValues=new Array();
    var sSymb="";
    
    arrLines=stockData.data.split('\r\n');
    
    for(i=0;i<arrLines.length-1;i++){
      arrLineValues=splitLine(arrLines[i]);
      sSymb+=trim(arrLineValues[24])+widget.getValue("Currency")+'=X+';      
    }
    sSymb=sSymb.substr(0,sSymb.length-1);
    var url='http://download.finance.yahoo.com/d/quotes.csv?s='+sSymb+'&f=l1&CW='+Math.random()*1000;
   
   /* var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
    params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 60;
    gadgets.io.makeRequest(url, _IG_MyCallback(fnPrepareStockData,stockData), params);
		*/
	  UWA.Data.request(
      url,
   {
     method: 'GET',
		 proxy: 'ajax',
     type: 'text',
     cache: 60,
     onComplete: fnPrepareStockData
   });
		
  }

  function fnPrepareStockData(currDataIn,stockDataIn){
    var arrLinesCD=new Array();
    var arrLinesSD=new Array();
    var arrLineValues=new Array();
    var currData = currDataIn.data;
    var stockData = stockDataIn.data;

    currData=currData.replace(/0.00/g,"1.00");
    arrStocks=new Array();
    
    arrLinesCD=currData.split('\r\n');
    arrLinesSD=stockData.split('\r\n');

    if (arrLinesSD.length>1){
      for(i=0;i<arrLinesSD.length-1;i++){
        arrLineValues=splitLine(arrLinesSD[i]);
        arrLineValues[26]=arrLinesCD[i];//Currency rate
        arrLineValues[30]=(isNaN(arrLineValues[4]))?0:myRound(arrLineValues[4]*arrStockQtys[i]*arrLineValues[26]);//Earned today in local currency
        if (isNaN(arrStockCurrRates[i])||trim(arrStockCurrRates[i])==""||widget.getValue("Currency")=="-"){
          arrStockCurrRates[i]=arrLineValues[26];
        }
        var TC = parseFloat(arrStockPrices[i]*arrStockCurrRates[i]*arrStockQtys[i])+parseFloat(arrStockTC[i]); //Total costs in local currency
        arrLineValues[31]=myRound((arrLineValues[6].replace("%","")*arrLineValues[26]*arrStockQtys[i])-TC);//Earned in local currency
        arrLineValues[32]=(isNaN(arrLineValues[3].replace(/\%/g,"").replace(/\+/g,"").replace(/\-/g,"")))?0:myRound(arrLineValues[3].replace(/\%/g,""));
        arrLineValues[34]=myRound(arrLineValues[6].replace("%","")*arrStockQtys[i]*arrLineValues[26]); //Stock Value in local currency
        arrLineValues[33]=0;
        if(arrStockQtys[i]>0&&arrStockPrices[i]>0){
          arrLineValues[33]=myRound(((arrLineValues[34] / TC)-1)*100);//Total Gain %
        }
        arrLineValues[35]=arrStockPrices[i];
        arrStocks[i]=arrLineValues;
      }
      bDataReady=true; //Data has been read and calculated
      fnUpdateValues();
    }
  }
  function fnRetry(){
    clearTimeout(iTmrRetry);
    if (!bDataReady){
      if (iSDRetry<10){
        iSDRetry++;
        var tmp='('+iSDRetry+')';
        document.getElementById('FooterMsg').innerHTML='Retrying stockdata request...'+tmp;
        fnLoadData(); 
      }else{
        document.getElementById('FooterMsg').innerHTML='Gave up loading stockdata';
      }
    }else{
      iTmrRetry=setTimeout('fnLoadData()',widget.getValue("UpdateInterval")-5000); 
      iSDRetry=0;
    }
  }
  function fnUpdateValues(){
    bAllReady=(bDataReady && bTablesReady);
    if (bAllReady){
      fnUpdateStockTable();
      fnUpdateProfit();
      fnUpdateSummary(0);
      document.getElementById("FooterMsg").innerHTML='Updated:'+fngetDate(false);
    }
    //gadgets.window.adjustHeight();
  }
  function fnUpdateProfit(){
    if (bAllReady){
      var iDayTotal=0;
      var iEarnTot=0;
      var iValTot=0;
      var bPD=document.getElementById("StockProfitDetails").style.display=="block";
      var bPS=document.getElementById("StockProfitSummary").style.display=="block";
      var sDTC;
      var sETC;
      for(i=0;i<arrStocks.length;i++){
        iDayTotal+=arrStocks[i][30];
        iEarnTot+=arrStocks[i][31];
        iValTot+=arrStocks[i][34];
        if (bPD){
          document.getElementById("ptc0"+i).innerHTML=arrStocks[i][2]; //Name
          document.getElementById("ptc1"+i).innerHTML=arrStocks[i][30]+'('+myRoundD(arrStocks[i][32],0)+'%)'; //
          document.getElementById("ptc2"+i).innerHTML=arrStocks[i][31]+'('+myRoundD(arrStocks[i][33],0)+'%)';
          document.getElementById("ptc3"+i).innerHTML=arrStocks[i][34];
          document.getElementById("ptc4"+i).innerHTML=arrStocks[i][24];
          document.getElementById("ptc5"+i).innerHTML=arrStocks[i][26];
          document.getElementById("ptc1"+i).style.color=fnNumToColor(arrStocks[i][32],"#000000");
          document.getElementById("ptc2"+i).style.color=fnNumToColor(arrStocks[i][31],"#000000");
        }
      }
      //Totals
      sDTC=fnNumToColor(iDayTotal,"#000000");
      sETC=fnNumToColor(iEarnTot,"#000000");
      iDayTotal=myRoundD(iDayTotal,0);
      iEarnTot=myRoundD(iEarnTot,0);
      iValTot=myRoundD(iValTot,0);
      if (bPD){
        document.getElementById("ptc1"+i).style.color=sDTC;
        document.getElementById("ptc1"+i).innerHTML='<b>'+iDayTotal+'</b>';
        document.getElementById("ptc2"+i).style.color=sETC;
        document.getElementById("ptc2"+i).innerHTML='<b>'+iEarnTot+'</b>';
        document.getElementById("ptc3"+i).innerHTML='<b>'+iValTot+'</b>';
        var tmp='('+widget.getValue("Currency")+')';
        document.getElementById("ptc0"+i).innerHTML='<div title="You can change the currency in gadget settings"><b>Total'+tmp+'</b></div>';
      }else if (bPS){
        document.getElementById("stct1").style.color=sDTC;
        document.getElementById("stct1").innerHTML='<b>'+iDayTotal+'</b>';
        document.getElementById("stct2").style.color=sETC;
        document.getElementById("stct2").innerHTML='<b>'+iEarnTot+'</b>';
        document.getElementById("stct3").innerHTML='<b>'+iValTot+'</b>';
      }
    }
  }
  function fnUpdateSummary(StockID){
    if (bAllReady){
      var img='<img width="192" height="96" src="http://ichart.finance.yahoo.com/z?s='+encodeURIComponent(arrStocks[StockID][1])+'&amp;t='+widget.getValue("ChartScope")+'&amp;l=on&amp;z=b">'; 
      if(document.getElementById("StockSummary").style.display=="block"){
        document.getElementById("SummaryChartTD").innerHTML=img;
        document.getElementById("SummaryNameTD").innerHTML=arrStocks[StockID][2];
        document.getElementById("SummaryDayRangeTD").innerHTML=arrStocks[StockID][20];
        document.getElementById("Summary52wkRangeTD").innerHTML=arrStocks[StockID][14];
        document.getElementById("Summary200AvgTD").innerHTML=arrStocks[StockID][19];
        document.getElementById("SummaryDayVolumeTD").innerHTML=arrStocks[StockID][12];
        document.getElementById("SummaryLastTradeTime").innerHTML=arrStocks[StockID][7]+' '+arrStocks[StockID][8];
      }else{
        document.getElementById("StockChart").innerHTML=img;
      }
    }
  }
  function fnUpdateStockTable(){
    var sName;
    var sbgColor;
    
    if (bAllReady){
      for(var i=0;i<arrStocks.length;i++){
        sName=arrStocks[i][2];
        if (sName==''||widget.getValue("NameColumn")==1){
          sName=arrStocks[i][1];
        }else if (widget.getValue("NameColumn")==40){//name(symbol)
          sName=arrStocks[i][2]+' ('+arrStocks[i][1]+')';
        }else if (!isNaN(arrStocks[i][21])){//If this is an option
          sName=sName.substr(0,sName.indexOf(" "))+" "+arrStocks[i][23].slice(4)+" "+myRound(arrStocks[i][21])+" "+arrStocks[i][22];
        }
        document.getElementById('stc'+i+'1').innerHTML='<a Title="'+trim(arrStocks[i][25])+'" id="stcn'+i+'" onmouseover="fnTPChart(1);fnUpdateSummary('+i+');" onmouseout="fnTPChart(0)" target="_new" href="http://finance.yahoo.com/q?s='+encodeURIComponent(arrStocks[i][1])+'">'+sName+'</a>'; 
        if(i%2==0){sbgColor='#FFFFFF';}else{sbgColor='#EFEFEF';}
        if(widget.getValue("Flashing")==1&&document.getElementById('stc'+i+'2').innerHTML!=''){
          document.getElementById('stc'+i+'2').style.background=fnNumToColor(parseFloat(arrStocks[i][3])-parseFloat(document.getElementById('stcc'+i+'2').innerHTML),sbgColor);
          setTimeout('document.getElementById("stc'+i+'2").style.background="'+sbgColor+'"',700);
        }
        var sClass="";
        //Multiplied with 1 equals toInt
        if ((arrStocks[i][6].replace("%","")*1)>(arrStockHi[i]*1) && (arrStockHi[i]*1)>0){
          sClass="HiAlert";
          sName=arrStockHi[i];
        }else if((arrStocks[i][6].replace("%","")*1)<(arrStockLo[i]*1) && (arrStockLo[i]*1)>0){
          sClass="LoAlert";
          sName=arrStockLo[i];
        }
        document.getElementById('stc'+i+'0').className=sClass;
        document.getElementById('stc'+i+'0').title="Hi="+arrStockHi[i]+"\nLo="+arrStockLo[i];
        document.getElementById('stc'+i+'2').innerHTML='<a target="_new" href='+'http://finance.yahoo.com/charts?s='+encodeURIComponent(arrStocks[i][1])+'#chart1:symbol='+encodeURIComponent(arrStocks[i][1])+';range=3m;indicator=volume;charttype=line;crosshair=on;logscale=on;source=><font id="stcc'+i+'2" color="'+fnNumToColor(arrStocks[i][3],"#000000")+'">'+arrStocks[i][widget.getValue("ChangeColumn")]+'</font></a>';
        if(arrStocks[i][1]!="-"){
          var k=3;
          for(var j=1;j<iConfCols+1;j++){
            if(widget.getValue("Column"+j)!='0'){
              document.getElementById('stc'+i+k).innerHTML='<div id="stcc'+i+k+'">'+arrStocks[i][widget.getValue("Column"+j)]+'</div>';
              k++;
            }
          }
        }else{
          document.getElementById('str'+i).style.background='#BCBCBC';
          document.getElementById('stc'+i+'1').innerHTML='';
          document.getElementById('stc'+i+'1').height='2px';
          document.getElementById('stc'+i+'2').innerHTML='';
        }
      }
    }
  }
  function fnUpdateSummary(StockID){
    if (bAllReady){
      var img='<img width="192" height="96" src="http://ichart.finance.yahoo.com/z?s='+encodeURIComponent(arrStocks[StockID][1])+'&amp;t='+widget.getValue("ChartScope")+'&amp;l=on&amp;z=b">'; 
      if(document.getElementById("StockSummary").style.display=="block"){
        document.getElementById("SummaryChartTD").innerHTML=img;
        document.getElementById("SummaryNameTD").innerHTML=arrStocks[StockID][2];
        document.getElementById("SummaryDayRangeTD").innerHTML=arrStocks[StockID][20];
        document.getElementById("Summary52wkRangeTD").innerHTML=arrStocks[StockID][14];
        document.getElementById("Summary200AvgTD").innerHTML=arrStocks[StockID][19];
        document.getElementById("SummaryDayVolumeTD").innerHTML=arrStocks[StockID][12];
        document.getElementById("SummaryLastTradeTime").innerHTML=arrStocks[StockID][7]+' '+arrStocks[StockID][8];
      }else{
        document.getElementById("StockChart").innerHTML=img;
//The page at https://sites.google.com/site/cnybroe/iGoogleStockGadget displayed insecure content from http://ichart.finance.yahoo.com/z?s=%5EGSPC&t=3m&l=on&z=b.
// (repeated 4 times)
      }
    }
  }
  function fnInsertSummary(){
    var sTemp='<hr class="HrDef"><table width="100%" border=0 cellspacing=0 cellpadding=0><tr><td id="SummaryChartTD" style="width:1%;height:98px"></td><td><table style="font-size:'+fsize+'" width="100%" border=0 cellspacing=0 cellpadding=0><tr><td style="width:5px"></td><td nowrap style="width:1%"><b>Name</b></td><td style="width:10px"></td><td id="SummaryNameTD" nowrap></td></tr><tr><td style="width:5px"></td><td nowrap style="width:1%"><b>Day range</b></td><td style="width:10px"></td><td id="SummaryDayRangeTD" nowrap></td></tr><tr><td style="width:5px"></td><td nowrap style="width:1%"><b>52 week range</b></td><td style="width:10px"></td><td id="Summary52wkRangeTD" nowrap></td></tr><tr><td style="width:5px"></td><td nowrap style="width:1%"><b>200 day avg.</b></td><td style="width:10px"></td><td id="Summary200AvgTD" nowrap></td></tr><tr><td style="width:5px"></td><td nowrap style="width:1%"><b>Volume</b></td><td style="width:10px"></td><td id="SummaryDayVolumeTD" nowrap></td></tr><tr><td style="width:5px"></td><td nowrap style="width:1%"><b>Trade time</b></td><td style="width:10px"></td><td id="SummaryLastTradeTime" nowrap></td></tr></table></td></tr></table>';
    document.getElementById('StockSummary').innerHTML=sTemp;
    document.getElementById("StockSummary").style.display='block';
    fnUpdateSummary(0);
  }
  function fnInsertProfitSummaryTable(){
    var sProfitTable='<hr class="HrDef"><table width="100%" border=0 cellspacing=0 cellpadding=0 style="font-size:'+fsize+'">';
    sProfitTable+='<tr width=100%><td nowrap>Gain today: </td><td id="stct1" nowrap></td><td width="10px" nowrap></td><td nowrap>Gain: </td><td id="stct2" nowrap></td><td width="10px" nowrap></td><td nowrap>Value: </td><td id="stct3" nowrap></td><td nowrap width="70%"></td></tr></table>';
    document.getElementById("StockProfitSummary").innerHTML=sProfitTable;
  }
  function fnInsertAdd(){
    var sCol='<Col width="16%"><Col width="16%"><Col width="16%"><Col width="16%"><Col width="16%"><Col width="16%">';
    var iCols=9;
    var sTDH='';
    var sTD='';
    var bCurr=widget.getValue("Currency")!="-";
    var sBGColor;
    if (bCurr){
      iCols=10;
      sCol='<Col width="14%"><Col width="14%"><Col width="14%"><Col width="14%"><Col width="14%"><Col width="14%"><Col width="14%">';
      sTDH='<td class="cellR">Exch.rate</td>';
    }
    var sTemp='<hr class="HrDef"><table border=0 id="tblSearch" cellspacing=0 cellpadding=0 style="font-size:'+fsize+'"><tr><td width="62px" align="left"><input type="text" style="font-size:'+fsize+';width:180px;color:#AAAAAA;" bclass="def" id="txtStockSymbol" name="txtStockSymbol" alt="Symbol" title="Enter symbol or company name" value="Enter symbol or company name" onFocus=txtFocus(this,1) onBlur=txtFocus(this,0) onKeyUp=fnSymbolSearch(this.value,"S")></td><td width="20px" align="left"><img width="12" height="12" style="cursor:hand;cursor:pointer;" onclick="var Temp=document.getElementById(\'txtStockSymbol\').value;fnAddStock(Temp);" title="Add" src="'+IMAGES_BASE+'AddStock.gif"></td></tr></table><div id="StockAddList" style="font-size:'+fsize+'" class="SearchList"></div>';
    var sLine='<tr style="height:1px;background-Color:BCBCBC"><td colspan='+iCols+'></td></tr>';
    var sConfigTable='<table style="width:100%;font-size:'+fsize+'" border=0 cellspacing=0 cellpadding=0>'+sCol+'<Col width="10px"><Col width="10px"><Col width="10px"><tr style="height:3px"><td colspan='+iCols+'></td></tr>'+sLine+'<tr style="font-weight: bold;"><td class="cellL">Symbol</td><td class="cellR" >Qty.</td><td class="cellR">Buy price</td><td class="cellR">comm.</td>'+sTDH+'<td class="cellR">High</td><td class="cellR">Low</td><td colspan=3></td></tr>'+sLine;
    for(i=0;i<arrStockSymbols.length;i++){
      if(i%2==0){sBGColor='#FFFFFF';}else{sBGColor='#EFEFEF';}
      if (bCurr){
        sTD='<td id="ctc4'+i+'" title="Click to change this item" onclick="fnEditStock(this)" onmouseover=this.style.backgroundColor="#dcdcdc" onmouseout=this.style.backgroundColor="'+sBGColor+'" class="cellR">'+arrStockCurrRates[i]+'</td>';
        }
      sConfigTable+='<tr style="background-Color:'+sBGColor+';"><td id="ctc0'+i+'" class="cellL" title="Click to change this item" onclick="fnEditStock(this)" onmouseover=this.style.backgroundColor="#dcdcdc" onmouseout=this.style.backgroundColor="'+sBGColor+'">'+arrStockSymbols[i]+'</td><td id="ctc1'+i+'" title="Click to change this item" onclick="fnEditStock(this)" onmouseover=this.style.backgroundColor="#dcdcdc" onmouseout=this.style.backgroundColor="'+sBGColor+'" class="cellR">'+arrStockQtys[i]+'</td><td id="ctc2'+i+'" title="Click to change this item" onclick="fnEditStock(this)" onmouseover=this.style.backgroundColor="#dcdcdc" onmouseout=this.style.backgroundColor="'+sBGColor+'" class="cellR">'+arrStockPrices[i]+'</td><td id="ctc3'+i+'" title="Click to change this item" onclick="fnEditStock(this)" onmouseover=this.style.backgroundColor="#dcdcdc" onmouseout=this.style.backgroundColor="'+sBGColor+'" class="cellR">'+arrStockTC[i]+'</td>'+sTD+'<td id="ctc5'+i+'" title="Click to change this item" onclick="fnEditStock(this)" onmouseover=this.style.backgroundColor="#dcdcdc" onmouseout=this.style.backgroundColor="'+sBGColor+'" class="cellR">'+arrStockHi[i]+'</td><td id="ctc6'+i+'" title="Click to change this item" onclick="fnEditStock(this)" onmouseover=this.style.backgroundColor="#dcdcdc" onmouseout=this.style.backgroundColor="'+sBGColor+'" class="cellR">'+arrStockLo[i]+'</td><td class="cellR" width="25px"><img class="cellR" id="ctc7'+i+'" width="10" height="10" style="cursor:hand;cursor:pointer;" onclick="fnDeleteStock('+i+')" src="'+IMAGES_BASE+'delete.gif" title="Remove"></td><td class="cellR" width="15px"><img id="ctc8'+i+'" width="10" height="10" style="cursor:hand;cursor:pointer;" onclick="fnMoveStock('+i+',0)" src="'+IMAGES_BASE+'MoveUp.gif" title="Move up"></td><td class="cellR" width="15px"><img id="ctc9'+i+'" width="10" height="10" style="cursor:hand;cursor:pointer;" onclick="fnMoveStock('+i+',1)" src="'+IMAGES_BASE+'MoveDown.gif" title="Move down"></td></tr>';
    }
    if (bCurr){
      sConfigTable+='<tr>'+sLine+'<td colspan=10 title="You can change the currency in gadget settings">Selected currency: '+widget.getValue("Currency")+'</td></tr>';
    }
    sConfigTable+='</table>';
    document.getElementById("StockAdd").innerHTML=sTemp+sConfigTable;
//The page at https://sites.google.com/site/cnybroe/iGoogleStockGadget displayed insecure content from http://stockportfoliogg.googlecode.com/svn/released/images/AddStock.gif.
//The page at https://sites.google.com/site/cnybroe/iGoogleStockGadget displayed insecure content from http://stockportfoliogg.googlecode.com/svn/released/images/delete.gif.
//The page at https://sites.google.com/site/cnybroe/iGoogleStockGadget displayed insecure content from http://stockportfoliogg.googlecode.com/svn/released/images/MoveUp.gif.
//The page at https://sites.google.com/site/cnybroe/iGoogleStockGadget displayed insecure content from http://stockportfoliogg.googlecode.com/svn/released/images/MoveDown.gif.
    //Hide move arrows with no function
    if (i>0){
      document.getElementById("ctc80").style.display="none";
      document.getElementById("ctc9"+(i-1)).style.display="none";
    }
  }
  function fnInsertTables(){
    bTablesReady=false;
    bAllReady=false;
    fnInsertFooter();
    fnInsertStockTable();
    fnToggleSummary(0);
    fnToggleProfit(true);
    fnToggleNews(0);
    //Show add if no stocks are configured
    if((trim(arrStockSymbols.join(","))==sDefStocks && arrStockSymbols.length==5) || document.getElementById("StockAdd").style.display=="block"){
      fnToggleAdd(1);
    }
    widget.setTitle(widget.getValue("CustomTitle"));
	if(debug){
	    widget.setTitle(widget.getValue("CustomTitle")+" - BETA");
	}
	
    bTablesReady=true; //All needed tables has been made
    fnUpdateValues();
  }
  function fnToggleProfit(bLoad){
    var bDet=(bLoad && widget.getValue("ShowProfit")=='Details') || (!bLoad && document.getElementById("StockProfitSummary").style.display=='block');
    var bSum=(bLoad && widget.getValue("ShowProfit")=='Summary') || (!bLoad && document.getElementById("StockProfitSummary").style.display=='none' && 
             document.getElementById("StockProfitDetails").style.display=='none');
    if(bSum){
        fnInsertProfitSummaryTable();
        widget.setValue("ShowProfit","Summary");
    }else if(bDet){
        fnInsertProfitDetailsTable();
        widget.setValue("ShowProfit","Details");
    }else{
        widget.setValue("ShowProfit","none");
    }
    document.getElementById("StockProfitDetails").style.display=(bDet)?'block':'none';
    document.getElementById("StockProfitSummary").style.display=(bSum)?'block':'none';
    fnUpdateProfit();
    //gadgets.window.adjustHeight();
  }
  function fnToggleSummary(bToggle){
    if(bToggle){
      if(document.getElementById("StockSummary").style.display=="none"){
        widget.setValue("ChartType","Summary");
        fnInsertSummary();
      }else{
        document.getElementById("StockSummary").style.display="none";
        widget.setValue("ChartType","ToolTip");
      }
    }else{
      if(widget.getValue("ChartType")=='Summary'){
        fnInsertSummary();
      }
    }
    //gadgets.window.adjustHeight();
  }
  function fnToggleAdd(ForceVisible){
    if((document.getElementById("StockAdd").style.display=="none" && bTablesReady==true)||ForceVisible==1){
      document.getElementById("StockAdd").style.display="block";
      fnInsertAdd();
    }else{
      document.getElementById("StockAdd").style.display="none";
    }
    //gadgets.window.adjustHeight();
  }
  function fnInsertFooter(){
    document.getElementById("Footer").innerHTML='<table border="0" cellspacing="0" celpadding="1px" width="100%"><tr><td colspan="7" style="height:2px"></td></tr><tr class="Footer"><td id="FooterMsg" nowrap>Awaiting stock data...</td><td width="18px"><img id="AddEditIcon" width="16" height="16" style="border:none;cursor:hand;cursor:pointer;" onclick="fnToggleAdd(0)" src="'+IMAGES_BASE+'AddEdit.gif" title="Show add/edit dialog"></td><td style="width:18px;"><img width="16" height="16" style="border:none;cursor:hand;cursor:pointer" onclick="fnToggleSummary(1)" src="'+IMAGES_BASE+'Summary.gif" title="Show stock summary"></td><td style="width:18px;"><img width="16" height="16" style="border:none;cursor:hand;cursor:pointer;" onclick="fnToggleProfit(false)" src="'+IMAGES_BASE+'money.gif" title="Show profit details"></td><td style="width:18px;"><img width="16" height="16" style="border:none;cursor:hand;cursor:pointer;" onclick="fnToggleNews(1);" src="'+IMAGES_BASE+'News.gif" title="Show news"/></td><td style="width:18px;"><a href="http://sites.google.com/site/cnybroe/iGoogleStockGadget/help-1" target="_blank"><img width="16" height="16" style="border:none;cursor:hand;cursor:pointer;" src="'+IMAGES_BASE+'help.gif" title="Help"></a></td><td style="width:18px;"><a href="http://ggforum.cnybroe.dk/default.aspx?g=forum&c=2" target="_blank"><img width="16" height="16" style="border:none;cursor:hand;cursor:pointer;" src="'+IMAGES_BASE+'ggroups.gif" title="Discuss this gadget with the developer and other users"></a></td></tr></table>';
  }
  function fnInsertStockTable(){
    var sBGColor;
    var sStockTable='<table border=0 cellspacing=0 width="100%" style="font-size:'+fsize+';" class="def">';
    var arrHeaderNames=',,,%,Change,Change(%),Last,Trade date,Trade time,Day open,Day low,Day high,Volume,Prev close,52 week range,Ask,Bid,Trend,50 day avg.,200 day avg.,Day range,strike,call/put,strike,Currency,,Exch.rate,,,,Gain today,Gain,,,,Buy price'.split(",");
    var sHead="";
    iConfCols=0;
    for(i=1;i<iStockCols+1;i++){
      if(widget.getValue("Column"+i)!='0'){
        iConfCols++;
        sHead+='<td class="cellR">'+arrHeaderNames[widget.getValue("Column"+i)]+'</td>';
      }
    }
    sStockTable+='<COLGROUP width="8px"><COLGROUP span="2" width="10%"><COLGROUP span="'+iConfCols+'" width="'+80/iConfCols+'%"><tr style="font-weight: bold;"><td style="padding-right:8px" title="Alerts"></td><td class="cellL">Name</td><td class="cellR"><div class="Chart" id="StockChart"></div>Change</td>';
    sStockTable+=sHead;
    sStockTable+='</tr><tr style="height:1px;background-Color:BCBCBC"><td colspan='+Number(iConfCols+3)+'></td></tr>';
    for(i=0;i<arrStockSymbols.length;i++){
      if(i%2==0){sBGColor='#FFFFFF';}else{sBGColor='#EFEFEF';}
      sStockTable+='<tr id="str'+i+'" style="background-Color:'+sBGColor+';"><td class="cellL" id="stc'+i+'0"></td><td class="cellL" id="stc'+i+'1">'+arrStockSymbols[i]+'</td>';
      for(j=2;j<iConfCols+3;j++){
        sStockTable+='<td class="cellR" id="stc'+i+j+'"></td>';
      }
      sStockTable+='</tr>';
    }
    sStockTable+='</table>';
    document.getElementById("StockData").innerHTML=sStockTable;
  }
  function fnInsertProfitDetailsTable(){
    var sCurr='';
    if (widget.getValue("Currency")=="-"){
      sCurr='style="visibility:hidden;"';
    }
    var sLine='<tr style="height:1px;background-Color:BCBCBC"><td colspan=6></td></tr>';
    var sProfitTable='<hr class="HrDef"><table width="100%" border=0 cellspacing=0 cellpadding=0 style="width:100%;font-size:'+fsize+'" class="def"><col width="10%"><col width="20%"><col width="25%"><col width="15%"><col width="15%"><col width="15%"><tr style="font-weight:bold;"><td class="cellL">Name</td><td class="cellR">Gain today</td><td class="cellR">Gain</td><td class="cellR">Value</td><td class="cellC" '+sCurr+'>Currency</td><td class="cellL" '+sCurr+'>Exch.rate</td></tr>'+sLine;
    for(i=0;i<arrStockSymbols.length+1;i++){
      if(i==arrStockSymbols.length){
        sProfitTable+=sLine;
      }
      sProfitTable+='<tr><td id="ptc0'+i+'" class="cellL"></td><td id="ptc1'+i+'" class="cellR"></td><td id="ptc2'+i+'" class="cellR"></td><td id="ptc3'+i+'" class="cellR"></td><td id="ptc4'+i+'" class="cellC" '+sCurr+'></td><td id="ptc5'+i+'" class="cellR" '+sCurr+'></td></tr>';
    }
    sProfitTable+='</table>';
    document.getElementById("StockProfitDetails").innerHTML=sProfitTable;
  }
  function fnToggleNews(bToggle){
    if (bToggle){
      if(document.getElementById("StockNews").style.display=="none"){
        document.getElementById("StockNews").innerHTML='<hr class="HrDef"><div class="loading">Loading ...</div>';
        var url='http://finance.yahoo.com/rss/headline?s='+encodeURIComponent(arrStockSymbols.join(","));
        /*var params = {};
        params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.FEED;
        params[gadgets.io.RequestParameters.NUM_ENTRIES] = 5;
        params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 600;
				
        gadgets.io.makeRequest(url, fnInsertNews, params);
				*/
				UWA.Data.request(
         url,
         {
           method: 'GET',
      		 proxy: 'feed',
           type: 'text',
           cache: 600,
           onComplete: fnInsertNews,
					 parameters: 'NUM_ENTRIES=5'
         });
        document.getElementById("StockNews").style.display="block";
        widget.setValue("ShowNews","1");
      }else{
        document.getElementById("StockNews").style.display="none";
        widget.setValue("ShowNews","0");
      }
    }else{
      if(widget.getValue("ShowNews")=='1'){
        fnToggleNews(1);
      }
    }
    //gadgets.window.adjustHeight();
  }
  function fnInsertNews(feedIn){
    var html="";
    var feed = feedIn.data;
    for(var i in feed.Entry){
	  html+='<tr><td width="5" valign="top"><img width="16" height="16" src="'+IMAGES_BASE+'Square.gif"></td><td><span><a href="'+feed.Entry[i].Link+'" target="_blank">';
      html+=feed.Entry[i].Title+'</a></span></td></tr>';
    }
    document.getElementById("StockNews").innerHTML='<hr class="HrDef"><table border="0" cellspacing="0" cellpadding="0" width="100%" style="font-size:'+fsize+'">'+html+'</table>';
    //gadgets.window.adjustHeight();
  }
  function fnSymbolSearch(symbol){
    if(trim(symbol)!=''){
      document.getElementById("StockAddList").innerHTML='Loading ...';
			var url='http://d.yimg.com/autoc.finance.yahoo.com/autoc?query='+encodeURIComponent(symbol)+'&callback=YAHOO.Finance.SymbolSuggest.ssCallback';
      /*var params = {};
      params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
      params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 3600;
      gadgets.io.makeRequest(url, fnSymbolSearchResponse, params);
*/

		  UWA.Data.request(
       url,
       {
           method: 'GET',
      		 proxy: 'ajax',
           type: 'text',
           cache: 3600,
           onComplete: fnSymbolSearchResponse
       });
    }else{
      document.getElementById("StockAddList").style.display="none";
    }
    //gadgets.window.adjustHeight();
  }
  function fnSymbolSearchResponse(ResponseTextIn){
    var iStart=0;
    var iEnd=0;
    var arrSearch="";
    var i=0;
    var sTemp="";
    var ResponseText = ResponseTextIn.data;
    var sLine='<tr style="height:1px;background-Color:BCBCBC"><td colspan=4></td></tr>';
    var sTable='<table width="100%" border=0 cellspacing=0 cellpadding=0 style="font-size:'+fsize+'" class="def">'+sLine+'<tr style="font-weight:bold;"><td>Symbol</td><td>Name</td><td>Type</td><td>Exchange</td></tr>'+sLine;
    if (ResponseText.indexOf('"Result":[]',1)<1){
      iStart=ResponseText.indexOf('[{',1)+2;
      iEnd=ResponseText.indexOf('}]',iStart);
      arrSearch=ResponseText.substring(iStart,iEnd).split("},{");
      for(i=0;i<arrSearch.length;i++){
        iStart=arrSearch[i].indexOf('"symbol":"',0)+10;
        iEnd=arrSearch[i].indexOf('","',iStart);
        sSymbol=arrSearch[i].substring(iStart,iEnd);
        sTable+='<tr style="cursor: pointer;" onmouseover=\'this.style.backgroundColor="#DCDCDC";\' onmouseout=\'this.style.backgroundColor="#FFFFFF";\' onclick=\'document.getElementById("txtStockSymbol").value="'+sSymbol+'"\'><td nowrap>'+sSymbol+'</td>';
        iStart=arrSearch[i].indexOf('"name": "',1)+9;
        iEnd=arrSearch[i].indexOf('","',iStart);
        sTable+='<td nowrap>'+arrSearch[i].substring(iStart,iEnd)+'</td>';
        iStart=arrSearch[i].indexOf('"typeDisp":"',1)+12;
        if (iStart>12){
          iEnd=arrSearch[i].indexOf('"',iStart);
          sTemp=arrSearch[i].substring(iStart,iEnd);
        }else{
          sTemp='Stock';
        }
        sTable+='<td nowrap>'+sTemp+'</td>';
        iStart=arrSearch[i].indexOf('"exchDisp":"',1)+12;
        if (iStart>12){
          iEnd=arrSearch[i].indexOf('"',iStart);
        }else{
          iStart=arrSearch[i].indexOf('"exch": "',1)+8;
          iEnd=arrSearch[i].indexOf('"',iStart);
        }
        sTable+='<td nowrap>'+arrSearch[i].substring(iStart,iEnd)+'</td></tr>';
      }
      sTable+='<tr><td colspan=4 class="Footer"><i>Search is limited to 10 hits.</i></td></tr></table>';
    }else{
      sTable+='<tr><td colspan=4>not found</td></tr></table>';
    }
    document.getElementById("StockAddList").innerHTML=sTable;
    document.getElementById("StockAddList").style.display="block";
    //gadgets.window.adjustHeight();
  }
  function fnEditStock(sender){
    if(sender.innerHTML.toLowerCase().indexOf("input",1)>0){return;}
    var sTemp=sender.innerHTML;
    var a="uha"+sender.id.replace("ctc","");
    var b=(sender.id.substr(3,1)==0)?'64px':'49px';
    var c=(sender.id.substr(3,1)==0)?'left':'right';
    var d='<input type="text" id="'+a+'" onkeypress="EditOnKey(event,this);" onBlur="EditOnBlur(this);" value="'+sTemp+'" class="def" style="font-size:'+fsize+';width:'+b+';height:18px;margin:0px;text-align:'+c+';" />';
    sender.innerHTML=d;
    document.getElementById(a).focus();
  }
  function EditOnBlur(s){
    var index=s.id.substr(4);
    var col=s.id.substr(3,1);
    if((col==0&&trim(s.value)!="")||(col>0&&!isNaN(s.value))){
      if(col==0){arrStockSymbols[index]=s.value;}
      if(col==1){arrStockQtys[index]=s.value;}
      if(col==2){arrStockPrices[index]=s.value;}
      if(col==3){arrStockTC[index]=s.value;}
      if(col==4){arrStockCurrRates[index]=s.value;}
      if(col==5){arrStockHi[index]=s.value;}
      if(col==6){arrStockLo[index]=s.value;}
      fnSavePrefs();
    }
    fnLoad();
  }
  function EditOnKey(e,s){
    if(e.keyCode==13){
      EditOnBlur(s);
    }
  }
  function fnTPChart(show){
    if(widget.getValue("ChartType")=='ToolTip' && show==1){
      document.getElementById("StockChart").style.display="block";
    }else{
      document.getElementById("StockChart").style.display="none";
    }
  }
  function fnDeleteStock(index){
    arrStockSymbols.splice(index,1);
    arrStockQtys.splice(index,1);
    arrStockPrices.splice(index,1);
    arrStockTC.splice(index,1);
    arrStockCurrRates.splice(index,1);
    arrStockHi.splice(index,1);
    arrStockLo.splice(index,1);
    fnSavePrefs();
    fnLoad();
  }
  function fnMoveStock(index,direction){
    var iAC;
    var iB;
    if(direction==1){
      if(index>arrStockSymbols.length-2){return;}
      iAC = index;
      iB = index+1;
    }else{
      if(index==0){return;}
      iAC = index-1;
      iB = index;
    }
      arrStockSymbols.splice(iAC,2,arrStockSymbols[iB],arrStockSymbols[iAC]);
      arrStockQtys.splice(iAC,2,arrStockQtys[iB],arrStockQtys[iAC]);
      arrStockPrices.splice(iAC,2,arrStockPrices[iB],arrStockPrices[iAC]);
      arrStockTC.splice(iAC,2,arrStockTC[iB],arrStockTC[iAC]);
      arrStockCurrRates.splice(iAC,2,arrStockCurrRates[iB],arrStockCurrRates[iAC]);
      arrStockHi.splice(iAC,2,arrStockHi[iB],arrStockHi[iAC]);
      arrStockLo.splice(iAC,2,arrStockLo[iB],arrStockLo[iAC]);
    fnSavePrefs();
    fnLoad();
  }
  function fnAddStock(Symbol){
    var tmp=Symbol.replace(/ /g,'');
    if(tmp.length>0 && Symbol!='Enter symbol or company name'){
      arrStockSymbols.push(tmp);
      arrStockQtys.push(0);
      arrStockPrices.push(0);
      arrStockTC.push(0);
      arrStockCurrRates.push("???");
      arrStockHi.push(0);
      arrStockLo.push(0);
      fnSavePrefs();
      fnLoad();
    }
  }
  function fnSavePrefs(){
    if (arrStockSymbols.length<iMaxStockNo+1){
      widget.setValue("StockSymbols",arrStockSymbols.join(","),"StockQtys",arrStockQtys.join(","),"StockHi",arrStockHi.join(","),"StockLo",arrStockLo.join(","),"StockPrices",arrStockPrices.join(","),"StockTC",arrStockTC.join(","),"StockCurrRates",arrStockCurrRates.join(","));
    }
  }
  function fnPrefsValidation(inp){
    //Check if no stocks are configured
    if (trim(inp.join(","))==""){
      arrStockSymbols=sDefStocks.split(",");
      arrStockQtys="100,0,0,200,300".split(",");
      arrStockPrices="235,0,0,0,0".split(",");
      arrStockTC="5,3,0,4,2".split(",");
      arrStockCurrRates="1,1,1,1".split(",");
      arrStockHi="500,10000,0,2,0.002".split(",");
      arrStockLo="300,6000,0,1,0.0005".split(",");
    }
    //Check for empty prefs
    for(var i=0;i<inp.length;i++){
      if (isNaN(arrStockQtys[i])||arrStockQtys[i].length==0){arrStockQtys[i]=0;}
      if (isNaN(arrStockPrices[i])||arrStockPrices[i].length==0){arrStockPrices[i]=0;}
      if (isNaN(arrStockTC[i])||arrStockTC[i].length==0){arrStockTC[i]=0;}
      if (isNaN(arrStockHi[i])||arrStockHi[i].length==0){arrStockHi[i]=0;}
      if (isNaN(arrStockLo[i])||arrStockLo[i].length==0){arrStockLo[i]=0;}
    }
    var tmp=widget.getValue("campaign_1")+"campaign_1"+widget.getValue("GadgetVersion")+"GadgetVersion"+
            widget.getValue("SettingVersion")+"SettingVersion"+widget.getValue("StockSymbols")+"StockSymbols"+
            widget.getValue("StockQtys")+"StockQtys"+widget.getValue("StockPrices")+"StockPrices"+
            widget.getValue("StockCurrRates")+"StockCurrRates"+widget.getValue("StockHi")+"StockHi"+
            widget.getValue("StockLo")+"StockLo"+widget.getValue("StockTC")+"StockTC"+
            widget.getValue("ShowProfit")+"ShowProfit"+widget.getValue("ChartType")+"ChartType"+
            widget.getValue("ShowNews")+"ShowNews"+widget.getValue("CustomTitle")+"CustomTitle"+
            widget.getValue("FontSize")+"FontSize"+widget.getValue("Currency")+"Currency"+
            widget.getValue("NameColumn")+"NameColumn"+widget.getValue("ChangeColumn")+"ChangeColumn"+
            widget.getValue("Column1")+"Column1"+widget.getValue("Column2")+"Column2"+
            widget.getValue("Column3")+"Column3"+widget.getValue("Column4")+"Column4"+
            widget.getValue("Column5")+"Column5"+widget.getValue("ChartScope")+"ChartScope"+
            widget.getValue("UpdateInterval")+"UpdateInterval"+widget.getValue("Flashing")+"Flashing"+
            widget.getValue("ChartScope")+"ChartScope"+widget.getValue("UpdateInterval")+"UpdateInterval"+
            widget.getValue("Flashing")+"Flashing";

    //print('PrefLength:'+tmp.length);

    //Check if too many stocks are configured
    if (arrStockSymbols.length>iMaxStockNo){
      //var miniMsg=new gadgets.MiniMessage(109);
      var divMess = widget.createElement("divMess");
      divMess.innerHTML = '<span style="background-Color:red;font-size:11px;"><a target="new" href="http://sites.google.com/site/cnybroe/iGoogleStockGadget/igoogle-preferences-limit">More than '+iMaxStockNo+' stocks has been configured. Please read more here.</a> &raquo;</span>';
     // var statusMsg = miniMsg.createStaticMessage(divMess);
    }
  }
  function fnMessage(){
    if((iPrefVersion*1)<(iVersion*1)){
      //var miniMsg=new gadgets.MiniMessage(109);
      var divMess = widget.createElement("divMess");
      //divMess.innerHTML = '<span style="font-size:11px;"><a target="new" href="http://sites.google.com/site/cnybroe/iGoogleStockGadget/release-notes" class="prostyle">Added buy price as column choice. Read more here.</a> &raquo;</span>';
      divMess.innerHTML = '<span style="font-size:11px;"><a target="new" href="http://ggforum.cnybroe.dk/default.aspx?g=posts&t=301" class="prostyle">iGoogle being phased out. Read the future plan here.</a> &raquo;</span>';
      //miniMsg.createDismissibleMessage(divMess, fnHideMess(iVersion));

	  }
    if (debug){
      //var miniMsg1=new gadgets.MiniMessage(109);
      var divMess1 = widget.createElement("divMess");
      divMess1.innerHTML = '<span style="background-Color:FF6633;font-size:11px;"><a target="new" href="http://www.google.dk/ig/directory?dpos=top&root=/ig&url=stockportfoliogg.googlecode.com/svn/released/portfolio.xml" class="prostyle">You are using the Beta version with debug enabled, please use the released version instead.</a> &raquo;</span>';
      //miniMsg1.createTimerMessage(divMess1, 15);
    }
    //var miniMsg2=new gadgets.MiniMessage(109);
    //var divMess2 = document.createElement("divMess");
    //divMess2.innerHTML = '<span style="background-Color:#FF6633;font-size:11px;"><a target="new" href="http://ggforum.cnybroe.dk/default.aspx?g=posts&m=787&#post787" class="prostyle">2011-08-11: Stockdata is currently unstable. Read more here.</a></span>';
    //miniMsg2.createTimerMessage(divMess2, 15);
    //gadgets.window.adjustHeight();
  }
  function fnHideMess(GadgetVersion){
    return function() {
    //gadgets.window.adjustHeight();
    widget.setValue("GadgetVersion",GadgetVersion);
    return true;
    }
  }
  function fngetDate(secs){
    var currentTime=new Date();
    var month=fnZeroPad(currentTime.getMonth()+1,2);
    var day=fnZeroPad(currentTime.getDate(),2);
    var year=currentTime.getFullYear();
    var hours=fnZeroPad(currentTime.getHours(),2);
    var minutes=fnZeroPad(currentTime.getMinutes(),2);
    if(secs){minutes+=':'+fnZeroPad(currentTime.getSeconds(),2);}
    return year+'-'+month+'-'+day+' '+hours+':'+minutes;
  }
  function fnZeroPad(num,length){
    var snum = num + '';
    while(snum.length < length) {
      snum = '0' + snum; 
    }
    return snum;
  }
  function trim(s){
    if (s){
      return s.replace(/^\s*/,"").replace(/\s*$/,"");
    }else{
      return "";
    }
  }
  function fnReadPrefs(){
    arrStockSymbols=widget.getValue("StockSymbols").split(",");
    arrStockQtys=widget.getValue("StockQtys").split(",");
    arrStockPrices=widget.getValue("StockPrices").split(",");
    arrStockTC=widget.getValue("StockTC").split(",");
    arrStockCurrRates=widget.getValue("StockCurrRates").split(",");
    arrStockHi=widget.getValue("StockHi").split(",");
    arrStockLo=widget.getValue("StockLo").split(",");
    iPrefVersion=widget.getValue("GadgetVersion");
  }
  function myRound(inp){
    var sInp = inp.toString();
    var i = sInp.indexOf(".");
    if (sInp.length>6 && i>-1 && !isNaN(inp)){
      if (i<6){
        i=6;
      }
      inp=sInp.substr(0,i)*1;
    }
    return inp;
  }
  function myRoundD(inp,digits){
    var x=Math.pow(10,digits);
    return Math.round(inp*x)/x;
  }
  function fnNumToColor(number,zeroColor){
    var sColor=zeroColor;
    if(!isNaN(parseFloat(number))){
      if(parseFloat(number)>0){sColor="#008200";}
      if(parseFloat(number)<0){sColor="#FF2200";}
    }
    return sColor;
  }
  function txtFocus(sender,focus){
    if (trim(sender.value)=="" || trim(sender.value)==sender.title){
      if (focus==1){
        sender.value="";
        sender.style.color='#000000';
      }else{
        sender.style.color='#AAAAAA';
        sender.value=sender.title;
      }
    }
  }
  function splitLine(inp){
    var out=new Array();
    out=inp.split(/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/);
    for(var i=0;i<out.length;i++){
      out[i]=out[i].replace(/"/g,"");
    }
    if(out.length!=26){
      out='N/A,Bad data,Bad data,0.00%,0.00,0.00 - 0.00%,0.00,01/01/1899,12:00am,0.00,0.00,0.00,100000,0.00,"0.00 - 0.00",0.00,0.00," ====== ",+0.00%,0.00%,"0.00 - 0.00","N/A","N/A","N/A","EUR","No exchange"'.split(',');  
    }
    if(out[0]!="N/A"){
      out[24]="???";
      out[25]=out[0].substr(0,out[0].indexOf("<"));
    }
    return out;
  }
  function print(msg){
    if (debug){
      var debug_html = document.getElementById("debug").innerHTML;
      if (document.getElementById("debug").style.display=='none'){
        document.getElementById("debug").style.display='block';
        //gadgets.window.adjustHeight();   
      }
      msg=fngetDate(1)+"; "+msg.toString()+"<br>";
      debug_html=msg+debug_html;
      document.getElementById("debug").innerHTML=debug_html;
    }
  }
  function _IG_MyCallback(callbackFunction, parameters) {
    var args = arguments;
    return function() {
      var combinedArgs = Array.prototype.slice.call(arguments);
      callbackFunction.apply(null,combinedArgs.concat(Array.prototype.slice.call(args,1)))
    }
  }
  
 //1-2-3 start
  fnInit();  
   </script>
  
  <script>
	  //gadgets.util.runOnLoadHandlers();
	</script>
	
	<script>
	 //window.google.csi.tickDl();
</script>
</body>
</html>